package cn.display.pixelworksx7.manager

import android.R.attr.startX
import android.R.attr.startY
import android.content.Context
import android.graphics.PixelFormat
import android.view.*
import android.view.View.OnTouchListener
import android.widget.Button
import androidx.core.content.getSystemService
import cn.display.pixelworksx7.R
import cn.display.pixelworksx7.util.ShellUtil
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit


class FloatWindowManager(private val context: Context) {

    private var floatingView: View? = null
    private var layoutParams: WindowManager.LayoutParams? = null
    private var startX: Float? = null
    private var startY: Float? = null
    fun createFloatingWindow(layoutInflater: LayoutInflater) {
        if (floatingView == null) {
            floatingView = layoutInflater.inflate(R.layout.float_view, null)
            layoutParams = WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT
            )
            var windowManager = context.getSystemService("window") as WindowManager
            layoutParams!!.gravity = Gravity.TOP or Gravity.END
            layoutParams!!.x = windowManager.defaultDisplay.width - layoutParams!!.width
            layoutParams!!.y = windowManager.defaultDisplay.height - layoutParams!!.height
            floatingView?.let {
                var closeFloat =  it.findViewById(R.id.close_float_window) as Button
                var moveFloat =  it.findViewById(R.id.move_float_window) as Button
                // var endRecord = it.findViewById(R.id.end_record_click_tap) as Button
               // var recordClickTap = it.findViewById<Button>(R.id.record_click_tap)
                var speedJoinRoom = it.findViewById<Button>(R.id.speed_join_room)
//                var recordClickTapText = recordClickTap.text
//                recordClickTap.setOnClickListener {
//                        var builder = OkHttpClient.Builder()
//                        // 设置连接超时，单位为毫秒
//                        builder.connectTimeout(10, TimeUnit.SECONDS);
//
//                        // 设置读取超时，单位为毫秒
//                        builder.readTimeout(600, TimeUnit.SECONDS);
//
//                        // 设置写入超时，单位为毫秒
//                        builder.writeTimeout(15, TimeUnit.SECONDS);
//                        val client = builder.build()
//                        val url = "http://192.168.31.179:8787/monitorClick"
//                        val request = Request.Builder()
//                            .url(url)
//                            .build()
//                        client.newCall(request).enqueue(object : okhttp3.Callback {
//                            override fun onFailure(call: okhttp3.Call, e: IOException) {
//                                println("Request failed: ${e.message}")
//                            }
//                            override fun onResponse(call: okhttp3.Call, response: Response) {
//                                if (response.isSuccessful) {
//                                    val responseBody = response.body?.string()
//                                    println("Response: $responseBody")
//                                } else {
//                                    println("Response error: ${response.message}")
//                                }
//                            }
//                        })
//                }
//                endRecord.setOnClickListener {
//                    val client = OkHttpClient()
//                    val url = "http://192.168.31.179:8787/stopMonitor"
//                    val request = Request.Builder()
//                        .url(url)
//                        .build()
//                    client.newCall(request).enqueue(object : okhttp3.Callback {
//                        override fun onFailure(call: okhttp3.Call, e: IOException) {
//                            println("Request failed: ${e.message}")
//                        }
//                        override fun onResponse(call: okhttp3.Call, response: Response) {
//                            if (response.isSuccessful) {
//                                val responseBody = response.body?.string()
//                                println("Response: $responseBody")
//                            } else {
//                                println("Response error: ${response.message}")
//                            }
//                        }
//                    })
//                }
                closeFloat.setOnClickListener {
                    removeFloatingWindow(windowManager = context.getSystemService("window") as WindowManager)
                }
                speedJoinRoom.setOnClickListener {
                    var taps = listOf(
                        mapOf("x" to "1941.2119", "y" to "1104.4521"),
                        mapOf("x" to "2572.5117", "y" to "1191.0732"),
                        mapOf("x" to "2792.6328", "y" to "1321.0674"),
                        mapOf("x" to "2782.9453", "y" to "1340.8164"),
                        mapOf("x" to "1869.1504", "y" to "1023.8310")
                    )
                    for (tap in taps) {
                        ShellUtil.execCommand("input tap ${tap["x"]} ${tap["y"]}",true)
                        Thread.sleep(200)
                    }
                }
                moveFloat.setOnTouchListener(object : OnTouchListener {
                    override fun onTouch(v: View, event: MotionEvent): Boolean {
                        when (event.action) {
                            MotionEvent.ACTION_DOWN -> {
                                startX = event.rawX
                                startY = event.rawY
                            }
                            MotionEvent.ACTION_MOVE -> {
                                val dx = event.rawX - startX!!
                                val dy = event.rawY - startY!!

                                layoutParams?.x = layoutParams?.x?.plus(dx.toInt())
                                layoutParams?.y = layoutParams?.y?.plus(dy.toInt())

                                (context.getSystemService("window") as WindowManager).updateViewLayout(floatingView, layoutParams)

                                startX = event.rawX
                                startY = event.rawY
                            }
                        }
                        return true
                    }
                })
            }

        }

    }

    fun showFloatingWindow(windowManager: WindowManager) {
        if (floatingView != null && layoutParams != null) {
            windowManager.addView(floatingView, layoutParams)
        }
    }

    fun removeFloatingWindow(windowManager: WindowManager) {
        floatingView?.let { windowManager.removeView(it) }
    }
}
